package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * @Author: cl
 * @Date: 2022/5/1 - 05 - 01
 * @Description:
 */
@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 根据ID查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public UserInfo findById(Long id) {

        UserInfo userInfo = userInfoMapper.selectById(id);
        return userInfo;
    }


    /**
     * 保存用户信息
     *
     * @param userInfo
     */
    @Override
    public void save(UserInfo userInfo) {

        userInfoMapper.insert(userInfo);
    }


    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    @Override
    public void update(UserInfo userInfo) {

        userInfoMapper.updateById(userInfo);
    }

    /**
     * 根据userId批量查找用户信息
     *
     * @param ids
     * @return
     */
    @Override
    public Map<Long, UserInfo> selectByIds(List<Long> ids, RecommendUserDto recommendUserDto) {
        List<UserInfo> userInfos = userInfoMapper.selectList(
                Wrappers.<UserInfo>lambdaQuery()
                        .in(UserInfo::getId, ids)
                        .lt(recommendUserDto.getAge() != null, UserInfo::getAge, recommendUserDto.getAge())
                        .eq(recommendUserDto.getGender() != null, UserInfo::getGender, recommendUserDto.getGender())
                        .like(recommendUserDto.getNickname() != null, UserInfo::getNickname, recommendUserDto.getNickname())
        );

        //使用CollUtil工具类封装到map中
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "id");
        return map;
    }

    /**
     * 分页查询所有用户
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public IPage<UserInfo> findAll(Integer page, Integer pagesize) {
        //分页条件
        Page<UserInfo> userInfoPage = new Page<>(page, pagesize);
        //按照创建时间排序
        Page<UserInfo> page1 = userInfoMapper.selectPage(userInfoPage,
                Wrappers.<UserInfo>lambdaQuery()
                        .orderByDesc(UserInfo::getCreated));
        return page1;
    }
}
